package fr.enseirb.mycub.activity.component.layer;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.database.Cursor;
import android.os.AsyncTask;
import fr.enseirb.mycub.component.map.OverlayBundleItem;
import fr.enseirb.mycub.component.map.bike.BikeStationOverlay;
import fr.enseirb.mycub.db.BikeDBConstants;

public abstract class UpdateOverlays extends AsyncTask<Void, Integer, Boolean> {

	private List<? extends OverlayBundleItem> mOverlays = null;
	private boolean mUpdateOnPostExecute = false;
	private Layer layer;
	
	public UpdateOverlays(Layer layer){
		this.layer = layer;
	}

	@Override
	protected Boolean doInBackground(Void... unused) {
		return updateListFromDb();
	}

	protected abstract int getOverlayCount();
	protected abstract Cursor getOverlayCursor();
	protected abstract void updateOverlays(Cursor cursor, Iterator<? extends OverlayBundleItem> it);
	
	private boolean updateListFromDb() {
		if (getOverlayCount() == 0 || isCancelled()) {
			return false;
		}
		Cursor cursor = getOverlayCursor();
		mOverlays = layer.mStationsOverlay.getOverlayList();
		Iterator<? extends OverlayBundleItem> it = mOverlays.iterator();
		updateOverlays(cursor, it);
		cursor.close();
		return true;
	}

	@Override
	protected void onPostExecute(Boolean isListCreated) {
		layer.mMapView.invalidate();
		if (layer.mStationsOverlay.isBalloonShowing()) {
			int pos = layer.mStationsOverlay.getLastFocusedIndex();
			if (pos >= 0 && pos < layer.mStationsOverlay.size()) {
				layer.mStationsOverlay.updateBalloonData(layer.mStationsOverlay
						.getItem(pos));
			}
		}
		layer.mUpdateOverlays = null;
		if (mUpdateOnPostExecute) {
			layer.executeUpdateOverlays();
		}
	}


	public void setUpdateOnPostExecute() {
		mUpdateOnPostExecute = true;
	}
}
